<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户管理</title>
<link rel="stylesheet" href="${ctx}/resources/layui/css/layui.css">
</head>
<body style="padding: 10px;">
	<!-- 搜索条件开始 -->
	<form class="layui-form" method="post" id="searchFrm" lay-filter="searchFrm">
		<div class="layui-form-item">
		    <div class="layui-inline">
		      <label class="layui-form-label">登录名:</label>
		      <div class="layui-input-inline">
		        <input type="text" name="loginname" autocomplete="off" class="layui-input">
		      </div>
		      <label class="layui-form-label">姓名:</label>
		      <div class="layui-input-inline">
		        <input type="text" name="realname" autocomplete="off" class="layui-input">
		      </div>
	      	</div>
	      	<div class="layui-inline">
		      <label class="layui-form-label">地址:</label>
		      <div class="layui-input-inline">
		        <input type="text" name="address" autocomplete="off" class="layui-input">
		      </div>
		      <label class="layui-form-label">电话:</label>
		      <div class="layui-input-inline">
		        <input type="text" name="phone" autocomplete="off" class="layui-input">
		      </div>
		    </div>
		    <div class="layui-inline">
		    	<label class="layui-form-label">身份证:</label>
		      <div class="layui-input-inline">
		        <input type="text" name="identity" autocomplete="off" class="layui-input">
		      </div>
		      <label class="layui-form-label">性别:</label>
			  <div class="layui-input-inline">
			     <input type="radio" name="sex" value="1" title="男">
			     <input type="radio" name="sex" value="0" title="女">
			  </div>
		      <div class="layui-input-inline">
		      	<button type="button" class="layui-btn layui-icon layui-icon-search"
					lay-submit="" lay-filter="doSearch">查询</button>
				<button type="reset" class="layui-btn layui-btn-warm layui-icon layui-icon-refresh">重置</button>
		      </div>
		    </div>
	   	</div> 
	</form>
	<!-- 搜索条件结束-->
	
	<!-- 数据表格开始 -->
	<table class="layui-hide" id="userTable" lay-filter="userTable"></table>
	<!-- 数据表格结束 -->
	<!-- 表格头部工具栏开始 -->
	<div style="display: none;" id="userToolbar">
		<button type="button" class="layui-btn" lay-event="add">添加</button>
		<button type="button" class="layui-btn layui-btn-danger" lay-event="batchDelete">批量删除</button>
	</div>
	<!-- 表格头部工具栏结束 -->
	<!-- 表格行工具栏开始 -->
	<div style="display: none;" id="userRowbar">
		<button type="button" class="layui-btn layui-btn-sm" lay-event="update">修改</button>
		<button type="button" class="layui-btn layui-btn-sm  layui-btn-warm" 
			lay-event="selectUserRole">分配角色</button>
		<button type="button" class="layui-btn layui-btn-sm  layui-btn-danger" 
			lay-event="resetUserPwd">重置密码</button>
		<button type="button" class="layui-btn layui-btn-sm  layui-btn-danger" 
			lay-event="delete">删除</button>
	</div>
	<!-- 表格行工具栏结束 -->
	
	<!-- 添加和修改弹出层开始 -->
	<div style="display: none;" id="addOrUpdateDiv">
		<form class="layui-form" method="post" lay-filter="dataFrm" id="dataFrm">
			<div class="layui-form-item" style="margin: 10px;">
				<!-- id，隐藏域，修改时使用 -->
				<input type="text" name="userid" hidden="">
			    <div class="layui-inline">
			      	<label class="layui-form-label">登录名:</label>
			      	<div class="layui-input-inline">
			        	<input type="text" id="loginname" name="loginname" placeholder="请输入登录名" lay-verify="required" autocomplete="off" class="layui-input">
			    	</div>
			      	<label class="layui-form-label">姓名:</label>
			      	<div class="layui-input-inline">
			        	<input type="text" name="realname" placeholder="请输入姓名" lay-verify="required" autocomplete="off" class="layui-input">
			    	</div>
			    </div>
			</div>
			<div class="layui-form-item" style="margin: 10px;">
			    <div class="layui-block">
			      	<label class="layui-form-label">身份证号:</label>
			      	<div class="layui-input-block">
			       		<input type="text" name="identity" placeholder="请输入身份证号" lay-verify="required" autocomplete="off" class="layui-input">
			     	</div>
			    </div>
	   		</div> 
	   		<div class="layui-form-item" style="margin: 10px;">
	   			<div class="layui-inline">
			      	<label class="layui-form-label">地址:</label>
			      	<div class="layui-input-inline">
			       		<input type="text" name="address" placeholder="请输入地址" autocomplete="off" class="layui-input">
			     	</div>
			      	<label class="layui-form-label">电话:</label>
			      	<div class="layui-input-inline">
			       		<input type="text" name="phone" placeholder="请输入电话" autocomplete="off" class="layui-input">
			     	</div>
			    </div>
	   		</div>
	   		<div class="layui-form-item" style="margin: 10px;">
	   			<div class="layui-inline">
	   				<label class="layui-form-label">职位:</label>
			      	<div class="layui-input-inline">
			       		<input type="text" name="position" placeholder="请输入职位" autocomplete="off" class="layui-input">
			     	</div>
			     	<label class="layui-form-label">是否可用:</label>
				    <div class="layui-input-inline">
				      	<input type="radio" name="available" value="1" title="是" checked="">
				      	<input type="radio" name="available" value="0" title="否">
				    </div>
	   			</div>
   			</div>
	   		
			<div class="layui-form-item" style="margin: 10px;">
				<div class="layui-inline">
					<label class="layui-form-label">性别:</label>
				    <div class="layui-input-block">
				      	<input type="radio" name="sex" value="1" title="男" checked="">
				      	<input type="radio" name="sex" value="0" title="女">
				    </div>
			    </div>
			</div>
			<div class="layui-form-item"  style="margin: 10px;text-align: right;" >
				<div class="layui-input-block">
					<button type="button" class="layui-btn layui-icon layui-icon-release"
						lay-submit="" lay-filter="doSubmit">保存</button>
					<button type="reset" class="layui-btn layui-btn-warm layui-icon layui-icon-refresh">重置</button>
				</div>
			</div>
		</form>
	</div>
	<!-- 添加和修改弹出层结束 -->
	<!-- 分配用户角色弹出层开始 -->
	<div style="display: none;margin: 10px;" id="selectUserRoleDiv">
		<table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
	</div>
	<!-- 分配用户 弹出层结束 -->
	

<script src="${ctx}/resources/layui/layui.js"></script>
<script>
	var tableIns;
	layui.use(['layer','table','form'], function() {
		var $ = layui.$;
		var layer = layui.layer;
		var table = layui.table;
		var form = layui.form;
		//初始化用户数据表格
		tableIns = table.render({
			    elem: '#userTable'					//渲染的目标对象
			    ,url:'${ctx}/user/userList.action'	//数据接口
			    ,title: '用户数据表'						//数据导出时的标题
			    ,toolbar:"#userToolbar"				//表头的工具条
			    ,height:"full-100"	
			    ,page: true			//是否启用分页
			    ,cols: [[			//列表数据
			      {type: 'checkbox', fixed: 'left'}
			      ,{field:'userid', title:'id', align:"center",width:"80"}
			      ,{field:'loginname', title:'登录名', align:"center",width:"120"}
			      ,{field:'realname', title:'姓名', align:"center",width:"120"}
			      ,{field:'sex', title:'性别', align:"center",width:"60",  templet:function(d){
			    	  return d.sex=="1"?"<span style='color:blue;'>男</span>":"<span style='color:red;'>女</span>";
			      }}
			      ,{field:'available', title:'可用', align:"center",width:"60",  templet:function(d){
			    	  return d.available=="1"?"<span style='color:green;'>是</span>":"<span style='color:red;'>否</span>";
			      }}
			      ,{field:'identity', title:'身份证号', align:"center",width:"200"}
			      ,{field:'address', title:'地址', align:"center",width:"120"}
			      ,{field:'phone', title:'电话', align:"center",width:"200"}
			      ,{field:'position', title:'职位', align:"center",width:"100"}
			      ,{fixed:'right', title:'操作', toolbar:"#userRowbar", align:"center",width:"300"}
			    ]]
			    ,done:function(res, curr, count){
                    //回调函数
                    //判断当前页码是否大于1
                    if(curr > 1 && res.data.length == 0){
                        //当前页码-1
                        var pageValue = curr - 1;
                        tableIns.reload({
                            page:{curr:pageValue}//修改页码
                        });
                    }
                }
			    
			  });
		//监听查询表单的提交
		form.on("submit(doSearch)",function(data){
 			if(data.field.sex == undefined){
				data.field.sex = "";
			}
			tableIns.reload({
				where: data.field
				,page: {
				  curr: 1 //重新从第 1 页开始
				}
			});		
		})
		 
		//1. 监听头工具栏事件 
		table.on("toolbar(userTable)",function(obj){
			switch (obj.event) {
			case "add":			
				openAddRole();
				break;
			case "batchDelete":
				batchDelete();
				break;
			}
		});
		//弹出层实例
		var mainIndex;
		//弹出层对应的提交url
		var url;
		var checkFlag = false;//标志 登录名称 是否可用
		function initLoginName(){
			$("#loginname").removeAttr("readonly");
			//绑定[登录名称]输入框的 失去焦点事件方法， 实现无刷新验证登录名称是否可用
	        $("#loginname").bind("blur",function () {
	            //获取登录名称
	            var loginName = $(this).val().trim();
	            //判断是否为空
	            if(loginName.length == 0){
	                layer.msg("登录名称不能为空");
	                return;
	            }
	            //发送验证的请求
	            $.post("${ctx}/user/checkLoginName.action",{"loginname":loginName},function (result) {
	            	checkFlag = result.success;
	                layer.msg(result.message);
	            },"json");
	        });
		}
		//表单验证规则
		form.verify({
			identity : function(value, item) {
				if (value.length != 18) {
					return "身份证长度不正确";
				}
			}
		})
		//打开添加用户弹出层
		function openAddRole() {
			mainIndex = layer.open({
				type:1
				,title:"添加用户"
				,content:$("#addOrUpdateDiv")
				,area:['700px']
				,success:function(ayero, index){
					//清空表单数据 jquery对象转dom对象，有reset函数
					$("#dataFrm")[0].reset();
					url = "${ctx}/user/addUser.action";
					checkFlag=false;
					initLoginName();
				}
			});
		}
		
		//监听添加或修改用户弹出层的提交操作
		form.on("submit(doSubmit)",function(data){
			//序列化表单数据
			if(!checkFlag){
                //登录名称可用
                layer.msg("登录名称[ "+data.field.loginname+" ]不可用!");
                return false;
            }
			var params = $("#dataFrm").serialize();
			$.post(url, params, function(result){
				if(result.success){
					//刷新数据表格
					tableIns.reload();
				}
				//显示响应提示信息
				layer.msg(result.message);
				//关闭弹出层
				layer.close(mainIndex);
			});
			//阻止表单提交
			return false;
		});
		
	 	//5. 监听行工具栏事件
		table.on('tool(userTable)', function(obj){
		  var data = obj.data; //获得当前行数据
		  switch (obj.event) {
			case 'update':
				openUpdateRole(data);
				break;
			case 'selectUserRole':
				openSelectUserRole(data);
				break;
			case 'resetUserPwd':
				resetUserPwd(data);
				break;
			case 'delete':
				deleteRole(data);
				break;
			}
		});
	 	
	 	//批量删除用户
	 	function batchDelete(){
	 		//获取当前选中行
            var checkStatus = table.checkStatus('userTable');
            //判断是否有选中行
            var length = checkStatus.data.length;
            if(length > 0){
                layer.confirm("确定要删除这 "+ length +" 条数据?",{icon:3,title:"提示"},function (index) {
                    var data = checkStatus.data;
                    var params = "";
                    $.each(data,function(i,item){
                    	if(i == 0){
                    		params += "ids="+item.userid;
                    	}else {
                    		params += "&ids="+item.userid;
                    	}
                    });
                    $.post("${ctx}/user/batchDeleteUser.action",params,function (result) {
                        if(result.success){
                            //刷新数据表格
                            tableIns.reload();
                        }
                        layer.msg(result.message);
                    });
                    //关闭提示框
                    layer.close(index);
                });
            }else {
                layer.msg("请选择要删除的行!");
            }
	 	}
	 	
		
		//打开修改用户弹出层
		function openUpdateRole(data) {
			mainIndex = layer.open({
				type:1
				,title:"修改用户"
				,content:$("#addOrUpdateDiv")
				,area:['700px']
				,success:function(ayero, index){
					//回显表单
					form.val('dataFrm',data);
					url = "${ctx}/user/updateUser.action";
					 //设置只读
                    $("#loginname").attr("readonly","readonly");
                    //移除失去焦点事件
                    $("#loginname").unbind("blur");
                    checkFlag = true;
				}
					  
			});
		}
		
		//删除用户
		function deleteRole(data){
			layer.confirm("是否删除用户 ["+data.realname+" ]?",{"icon":3,"title":"提示"},function (index) {
                $.post("${ctx}/user/deleteById.action",{"userid":data.userid},function (result) {
                    if(result.success){
                        //刷新数据表格
                        tableIns.reload();
                    }
                    layer.msg(result.message);
                }, "json");
            });
	 	}
		//重置用户密码
		function resetUserPwd(data){
			layer.confirm("确定要重置用户 ["+data.realname+" ]的登录密码?",{"icon":3,"title":"提示"},function (index) {
                $.post("${ctx}/user/resetUserPwd.action",{"userid":data.userid},function (result) {
                    if(result.success){
                        //刷新数据表格
                        tableIns.reload();
                    }
                    layer.msg(result.message);
                }, "json");
            });
		}
		 	
		//打开分配角色菜单的弹出层
		function openSelectUserRole(data){
			 mainIndex = layer.open({
	                type:1,
	                title:"为[  "+data.realname+" ]分配角色",
	                area:["500px","500px"],
	                content:$("#selectUserRoleDiv"),
	                success:function () {
	                    //初始化分配角色表格
	                    initRoleTable(data);
	                },
	                btn:["确认","取消"],
	                yes:function (index, layero) {
	                	var roleData = table.checkStatus('roleTable').data; 
                        var params = "userid="+data.userid;
                        //循环遍历选中的角色id
                        $.each(roleData, function(i,item){
                        	params += "&ids="+item.roleid;
                        });
                        //uid 用户id, ids要分配的角色id
                        $.post("${ctx}/user/saveUserRole.action",params,function (result) {
                            layer.msg(result.message);
                        });
                        //关闭当前窗口
                        layer.close(mainIndex);
	                }
	            });
		}
		//初始化分配角色数据表格
		function initRoleTable(data){
			table.render({
				elem: '#roleTable'					//渲染的目标对象
			    ,url:'${ctx}/user/initRoleTableByUserId.action'	//数据接口
		    	,where:{    //请求参数
                    "userid":data.userid
                }
			    ,page: true			//是否启用分页
			    ,cols: [[			//列表数据
			      {type: 'checkbox', fixed: 'left'}
			      ,{field:'roleid', title:'id', align:"center"}
			      ,{field:'rolename', title:'角色名称', align:"center"}
			      ,{field:'roledesc', title:'角色描述', align:"center"}
			    ]]
			  });
		}
	});
</script>
</body>
</html>